package com.lu.servlet;

import com.lu.dao.impl.NewsUsersDaoImpl;
import com.lu.entity.NewsUsers;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/Servlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");

        NewsUsers newsUsers = new NewsUsersDaoImpl().getOneUser(uname, upwd);
        if (newsUsers != null) {
            // 登录成功后 把有效账户存入会话
            req.getSession().setAttribute("currentUser", newsUsers);
            // 有效账户同时存入 在线人的集合中 整个集合存入application中
            List<NewsUsers> currentUserList = (List<NewsUsers>) req.getServletContext().getAttribute("currentUserList");
            if (currentUserList == null) {
                currentUserList = new ArrayList<>();
            }
            if (!currentUserList.contains(newsUsers)) {
                currentUserList.add(newsUsers);
            }
            req.getServletContext().setAttribute("currentUserList", currentUserList);

//            Cookie cookie = new Cookie("currentUname", uname);// 设定cookie
//            resp.addCookie(cookie); // 响应发回给客户端
            // 下面的代码只能使用 响应重定向 不能使用请求转发
            resp.sendRedirect("GetSomeNewsByPageServlet");
            //request.getRequestDispatcher("admin.jsp").forward(request, response);
        } else {
            resp.sendRedirect("index.jsp");
        }


        out.flush();
        out.close();
    }
}
